import { ThemeProvider, Dialog, DialogTitle } from "@mui/material";
import { useCallback, useState } from "react";
import TabBar from "./layout/TabBar";
import Notice from "./components/Notice";
import * as Theme from "./theme";
import Connect from "./components/Connect";
import { Collections, DbInfo } from "./api/types";
import DatabaseSide from "./components/DatabaseSide";
import styled from "styled-components";
import { getCollections } from "./api/mongo";
import CollectionSide from "./components/CollectionSide";
import DataTable from "./components/DataTable";
import { DBInfoContext } from "./context/DBInfoContext";

function App() {
  const [mode, setMode] = useState<"light" | "dark">("light");
  const [dbInfo, setDbInfo] = useState<Partial<DbInfo>>({});
  const [newDbLoad, setNewDbLoad] = useState(0);
  const [collections, setCollections] = useState<Collections>([]);
  const [selectedCollection, setSelectedCollection] = useState("");

  const toggleTheme = useCallback(
    () => setMode(prev => (prev === "dark" ? "light" : "dark")),
    []
  );

  const closeConnect = useCallback(() => {
    setDbInfo({});
    setCollections([]);
    setSelectedCollection("");
  }, []);

  const selectedDatabase = useCallback(
    async (databaseName: string) => {
      const { data } = await getCollections({
        id: dbInfo.id as string,
        databaseName,
        type: "mongo",
      });
      if (data) {
        console.log(data);
        // 渲染新collections
        setCollections(data.collections);
        // 渲染新的数据展示
        setSelectedCollection("");
        // 切换选中数据库
        setDbInfo({ ...dbInfo, databaseName });
      }
      // 关闭对话框
      setNewDbLoad(Math.random());
    },
    [dbInfo]
  );

  const handleConnect = useCallback((info: DbInfo) => {
    setDbInfo(info);
    if (info.databaseName !== "test") {
      getCollections({
        id: info.id,
        databaseName: info.databaseName,
        type: "mongo",
      }).then(({ data }) => {
        if (data) {
          setCollections(data.collections);
        }
      });
    }
  }, []);

  const findCollection = useCallback((collection: string) => {
    setSelectedCollection(collection);
  }, []);

  return (
    <ThemeProvider theme={Theme[mode]}>
      <Theme.GlobalStyle />
      <Dialog open={!dbInfo.id}>
        <DialogTitle>连接数据库-MongoDB</DialogTitle>
        <Connect handleConnect={handleConnect} />
      </Dialog>
      <DBInfoContext.Provider value={dbInfo as DbInfo}>
        <Container>
          <TabBar
            mode={mode}
            toggleTheme={toggleTheme}
            closeConnect={closeConnect}
          />
          <Center>
            {dbInfo.id ? (
              <DatabaseSide
                dbInfo={dbInfo as DbInfo}
                selectedDatabase={selectedDatabase}
                newDbLoad={newDbLoad}
              />
            ) : null}
            {collections.length ? (
              <CollectionSide
                onDoubleClick={findCollection}
                collections={collections}
              />
            ) : null}
            {selectedCollection ? (
              <DataTable
                id={dbInfo.id as string}
                selectedCollection={selectedCollection}
              />
            ) : null}
          </Center>
        </Container>
      </DBInfoContext.Provider>
      <Notice />
    </ThemeProvider>
  );
}

export default App;

const Center = styled.main`
  flex: 1;
  overflow: hidden;
  display: flex;
`;

const Container = styled.div`
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
`;
